package com.ljx.offer;

/**
 * @author 李捷禧
 * Date: 2023/3/24
 * ClassName: C_12
 */

public class C_12 {
    /***
     * 使用的是一个深度搜索
     * @param board
     * @param word
     * @return
     */
    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if(dfs(board,words,i,j,0)) return true;
            }
        }
        return false;
    }

    /**
     * 四个方向递归搜索
     * @param board
     * @param word
     * @param i
     * @param j
     * @param k words的数组下标
     * @return
     */
    private boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        if(board.length <= i || board[0].length <= j || i < 0 || j < 0 || board[i][j] != word[k]) return false;
        if(k == word.length - 1) return true;
        //board[i][j] == words[k]的时候，就将board[i][j]标记为空值
        board[i][j] = '\0';
        //要是有一个方向符合board[i][j] == words[k]，就一直搜索下去，直到k == words.length - 1
        boolean res = dfs(board,word,i+1,j,k+1) || dfs(board,word,i-1,j,k+1) ||
                        dfs(board,word,i,j+1,k+1) || dfs(board,word,i,j-1,k+1);
        //如果四个方向没有搜索到就返回原来的值
        board[i][j] = word[k];
        return res;
    }
}
